package com.wt.admin.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wt.admin.config.SecUtils;
import com.wt.admin.entity.SmsCode;
import com.wt.admin.entity.WqunAccount;
import com.wt.admin.entity.WqunBlog;
import com.wt.admin.entity.WqunCommunity;
import com.wt.admin.entity.rewentity.LoginUser;
import com.wt.admin.service.WqunAdminService;
import com.wt.admin.service.WqunCommunityService;
import com.wt.admin.service.impl.UserDetailsServiceImpl;
import com.wt.admin.service.impl.WqunAdminServiceImpl;
import com.wt.admin.service.impl.WqunCommunityServiceImpl;
import com.wt.commonutils.R;
import com.wt.oos.Upload;
import com.wt.redis.RedisCache;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Api(tags = "账号管理")
@RestController
@RequestMapping("/wqunAccountController")
@CrossOrigin
public class WqunAccountController {
    @Autowired
    WqunAdminService wqunAdminService = new WqunAdminServiceImpl();

    @Autowired
    WqunCommunityService wqunCommunityService = new WqunCommunityServiceImpl();

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private UserDetailsServiceImpl userDetailsService;


    //修改密码
    @ApiOperation("找回密码修改密码")
    @GetMapping("/findAccountPass/{email}/{pass}")
    public R findAccountPass(@PathVariable("email") String email,@PathVariable("pass") String pass){

        QueryWrapper<WqunAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email",email);
        WqunAccount findMyAccountMess = wqunAdminService.getOne(queryWrapper);
        if(findMyAccountMess == null){
            return R.error().message("该邮箱未注册");
        }
        pass = SecUtils.passBcrypt(pass);//密码加密
        findMyAccountMess.setPass(pass);
        boolean updateMyEmail = wqunAdminService.updateById(findMyAccountMess);
        if(updateMyEmail){
            return R.ok().message("密码修改成功");
        }else{
            return R.error().message("密码修改失败");
        }
    }

    //修改密码
    @ApiOperation("管理员密码重置")
    @GetMapping("/resettingAccountPass/{uid}")
    @PreAuthorize("hasAnyAuthority('admin:wqunAccountController:resettingAccountPass')")
    public R resettingAccountPass(@PathVariable("uid") String uid){
        QueryWrapper<WqunAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",uid);
        WqunAccount findMyAccountMess = wqunAdminService.getOne(queryWrapper);
        String pass = SecUtils.passBcrypt("123456");//密码加密
        findMyAccountMess.setPass(pass);
        boolean updateMyEmail = wqunAdminService.updateById(findMyAccountMess);
        if(updateMyEmail){
            return R.ok().message("密码重置成功");
        }else{
            return R.error().message("密码重置失败");
        }
    }

    //修改密码
    @ApiOperation("修改密码")
    @GetMapping("/changeAccountPass/{pass}")
    @PreAuthorize("hasAnyAuthority('wqunAccountController:changeAccountPass')")
    public R updateMyEmail(@PathVariable("pass") String pass){
        String id = SecUtils.getUserMess().getId();

        QueryWrapper<WqunAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id);
        WqunAccount findMyAccountMess = wqunAdminService.getOne(queryWrapper);
        pass = SecUtils.passBcrypt(pass);//密码加密
        findMyAccountMess.setPass(pass);
        boolean updateMyEmail = wqunAdminService.updateById(findMyAccountMess);
        if(updateMyEmail){
            return R.ok().message("密码修改成功");
        }else{
            return R.error().message("密码修改失败");
        }
    }

    //修改邮箱
    @ApiOperation("修改邮箱")
    @GetMapping("/updateMyEmail/{email}/{code}")
    @PreAuthorize("hasAnyAuthority('wqunAccountController:updateMyEmail')")
    public R updateMyEmail(@PathVariable("email") String email,@PathVariable("code") String code){

        QueryWrapper<WqunAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email",email);
        if(wqunAdminService.count(queryWrapper) > 0){
            return R.error().message("该邮箱已经存在，请登录该邮箱账号，或找回该账号密码");
        }

        String emailCode = (String) redisTemplate.opsForValue().get(email);//获取验证码
        if(emailCode == null || emailCode.equals("")){
            return R.error().message("未发送验证码或验证码已过期，请重新发送");
        }
        if(!emailCode.equals(code)){
            return R.error().message("验证码错误，请重新输入");
        }

        String phone = SecUtils.getUserMess().getPhone();
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",phone);
        WqunAccount findMyAccountMess = wqunAdminService.getOne(queryWrapper);

        findMyAccountMess.setEmail(email);
        boolean updateMyEmail = wqunAdminService.updateById(findMyAccountMess);
        if(updateMyEmail){
            return R.ok().message("邮箱修改成功");
        }else{
            return R.error().message("邮箱修改失败");
        }
    }

    //查看自己的所有信息
    @ApiOperation("查看自己的所有信息")
    @GetMapping("/findMyAccountMess")
    @PreAuthorize("hasAnyAuthority('wqunAccountController:findMyAccountMess')")
    public R findMyAccountMess(){
        String phone = SecUtils.getUserMess().getPhone();
        QueryWrapper<WqunAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id","nick_name","sex","user_type","email","avatar","created_time","user_name","phone");
        queryWrapper.eq("phone",phone);
        WqunAccount findMyAccountMess = wqunAdminService.getOne(queryWrapper);
        if(findMyAccountMess!=null){
            return R.ok().data("findMyAccountMess",findMyAccountMess);
        }else{
            return R.error().message("无此用户");
        }
    }

    //查看自己的权限
    @ApiOperation("查看自己的所有信息")
    @GetMapping("/findMyAccountType")
    @PreAuthorize("hasAnyAuthority('wqunAccountController:findMyAccountType')")
    public R findMyAccountType(){
        String phone = SecUtils.getUserMess().getPhone();
        QueryWrapper<WqunAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("user_type");
        queryWrapper.eq("phone",phone);
        WqunAccount findMyAccountType = wqunAdminService.getOne(queryWrapper);
        if(findMyAccountType!=null){
            return R.ok().data("findMyAccountType",findMyAccountType.getUserType());
        }else{
            return R.error().message("无此用户");
        }
    }

    //查询指定id用户，可公开信息
    @ApiOperation("查询所有账号信息")
    @GetMapping("/findAccountPublicById/{id}")
    @PreAuthorize("hasAnyAuthority('wqunAccountController:findAccountPublicById')")
    public R findAccountPublicById(@PathVariable("id") String id){
        QueryWrapper<WqunAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("nick_name","sex","user_type","email","avatar","created_time");
        queryWrapper.eq("id",id);
        WqunAccount findAccountPublicById = wqunAdminService.getOne(queryWrapper);
        if(findAccountPublicById!=null){
            return R.ok().data("findAccountPublicById",findAccountPublicById);
        }else{
            return R.error().message("无此用户");
        }
    }

    //查询所有账号信息
    @ApiOperation("查询所有账号信息")
    @GetMapping("/findAllAccount")
    public R findAllAccount(){
        QueryWrapper<WqunAccount> queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("id");
        List<WqunAccount> allArticle = wqunAdminService.list(queryWrapper);
        return R.ok().data("userList",allArticle);
    }



    //管理员查询所有账号信息(公共可读)
    @ApiOperation("查询所有账号信息")
    @GetMapping("/admin/findAllAccountPublic")
    public R findAllAccountPublic(){
        QueryWrapper<WqunAccount> queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("id");
        queryWrapper.select("id","nick_name","sex","user_type","email","avatar","created_time");
        List<WqunAccount> findAllAccountPublic = wqunAdminService.list(queryWrapper);
        return R.ok().data("findAllAccountPublic",findAllAccountPublic);
    }

    //分页查询所有账号
    @ApiOperation("分页查询所有账号")
    @GetMapping("/findAccountPage/{pageSize}/{currentPage}/{selectFind}/{selectFindValue}")
    @PreAuthorize("hasAnyAuthority('admin:wqunAccountController:findAccountPage')")
    public R findAccountPage(@PathVariable int pageSize,@PathVariable int currentPage,@PathVariable String selectFind,@PathVariable String selectFindValue){
        return wqunAdminService.findAccountPage(pageSize,currentPage,selectFind,selectFindValue);
    }


    @ApiOperation("管理员修改账号")
    @PostMapping("/changeAccount")
    @PreAuthorize("hasAnyAuthority('admin:wqunAccountController:changeAccount')")
    public R changeAccount(@RequestBody WqunAccount wqunAccount){
        WqunAccount oldAccount = wqunAdminService.getById(wqunAccount.getId());
        boolean deleteImgRes = true;
        //进行了图片修改deleteUserByI
        if(oldAccount.getAvatar() != null && oldAccount.getAvatar().length() != 0 && !oldAccount.getAvatar().equals(wqunAccount.getAvatar())){
            QueryWrapper<WqunCommunity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("uid",wqunAccount.getId());
            List<WqunCommunity> list = wqunCommunityService.list(queryWrapper);
            for (WqunCommunity wqunCommunity : list) {
                wqunCommunity.setAvatar(wqunAccount.getAvatar());
                boolean updateAvatar = wqunCommunityService.updateById(wqunCommunity);
            }
            deleteImgRes = Upload.deleteUploadImg(oldAccount.getAvatar());
        }
        if(deleteImgRes){
            boolean res = wqunAdminService.updateById(wqunAccount);
            if(res){
                //修改redis中缓存的用户权限
                String redisKey = "login:" + wqunAccount.getId();
                LoginUser cacheObject = redisCache.getCacheObject(redisKey);
                if(cacheObject != null){
                    UserDetails userDetails = userDetailsService.loadUserByUsername(wqunAccount.getPhone());
                    redisCache.setCacheObject(redisKey,userDetails);
                }
            }
            return res?R.ok().message("修改成功"):R.error().message("修改失败");
        }else{
            return R.error().message("修改失败");
        }
    }



    @ApiOperation("修改自己账号")
    @PostMapping("/changeMyAccount")
    @PreAuthorize("hasAnyAuthority('wqunAccountController:changeMyAccount')")
    public R changeMyAccount(@RequestBody WqunAccount wqunAccount){
        String userUid = SecUtils.getUserMess().getId();
        if(!wqunAccount.getId().equals(userUid)){
            return R.error().message("异常请求");
        }
        WqunAccount oldAccount = wqunAdminService.getById(wqunAccount.getId());
        boolean deleteImgRes = true;
        //进行了社区信息图片修改
        if(oldAccount.getAvatar() != null && oldAccount.getAvatar().length() != 0 && !oldAccount.getAvatar().equals(wqunAccount.getAvatar())){
            QueryWrapper<WqunCommunity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("uid",wqunAccount.getId());
            List<WqunCommunity> list = wqunCommunityService.list(queryWrapper);
            for (WqunCommunity wqunCommunity : list) {
                wqunCommunity.setAvatar(wqunAccount.getAvatar());
                boolean updateAvatar = wqunCommunityService.updateById(wqunCommunity);
            }
            deleteImgRes = Upload.deleteUploadImg(oldAccount.getAvatar());
        }
        if(deleteImgRes){
            boolean res = wqunAdminService.updateById(wqunAccount);
            return res?R.ok().message("修改成功"):R.error().message("修改失败");
        }else{
            return R.error().message("修改失败");
        }
    }



    //修改密码验证码验证
    @ApiOperation("用户信息修改-修改密码验证码验证")
    @PostMapping("/changePassCode")
    public R changePassCode(@RequestBody SmsCode smsCode){
        //登录验证
        String token =  wqunAdminService.loginCode(smsCode);
        //将登录凭证发给前端
        return R.ok();
    }



    //账号总数
    @ApiOperation("账号总数")
    @GetMapping("/accountNumById")
    @PreAuthorize("hasAnyAuthority('wqunAccountController:accountNumById')")
    public R accountNumById(){
        QueryWrapper queryWrapper = new QueryWrapper();
        int accountNumById = wqunAdminService.count(queryWrapper);
        return accountNumById!=0?R.ok().data("accountNumById",accountNumById):R.error();
    }


    //7日内新增
    @ApiOperation("7日内新增")
    @GetMapping("/accountAddAtSeven")
    @PreAuthorize("hasAnyAuthority('wqunAccountController:accountAddAtSeven')")
    public R accountAddAtSeven(){
        QueryWrapper queryWrapper = new QueryWrapper();
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String endTime = dateFormat.format(date);
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DATE, - 7);
        Date startDay = c.getTime();
        String startTime = dateFormat.format(startDay);
        queryWrapper.ge("created_time",startTime);
        queryWrapper.le("created_time",endTime);
        int accountAddAtSeven = wqunAdminService.count(queryWrapper);
        return accountAddAtSeven!=0?R.ok().data("accountAddAtSeven",accountAddAtSeven):R.error();
    }

    //删除账号
    @ApiOperation("删除账号")
    @GetMapping("/deleteById/{id}")
    @PreAuthorize("hasAnyAuthority('admin:wqunAccountController:deleteById')")
    public R deleteById(@PathVariable String id){
        WqunAccount byId = wqunAdminService.getById(id);
        byId.setIsDelete("1");
        boolean deleteRes = wqunAdminService.updateById(byId);
        return deleteRes?R.ok().message("删除成功"):R.error().message("删除失败");
    }

    @ApiOperation("恢复账号")
    @GetMapping("/restoreUserById/{id}")
    @PreAuthorize("hasAnyAuthority('admin:wqunAccountController:restoreUserById')")
    public R restoreUserById(@PathVariable String id){
        WqunAccount byId = wqunAdminService.getById(id);
        byId.setIsDelete("0");
        boolean restoreRes = wqunAdminService.updateById(byId);
        return restoreRes?R.ok().message("恢复成功"):R.error().message("恢复失败");
    }



}
